package com.sugou.web.ctrl;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sugou.dao.support.Dao;

@Controller
@RequestMapping("/")
@SuppressWarnings({"rawtypes"})
@Scope("prototype")
public class IndexCtrl extends WebControllerSupport{
	private static final long serialVersionUID = 6403569331341197962L;

	@Resource(name="baseDao")
	private Dao dao;
	
	private static final Pattern ADDR_REGEX=Pattern.compile("addr_(.+)");

	private static final Pattern P_REGEX=Pattern.compile("p_(.+)");
	
	private static final Pattern SRV_REGEX=Pattern.compile("srv_(.+)");
	
	private static final Pattern AREA_REGEX=Pattern.compile("a_(\\d+)");
	
	private static final Pattern TYPE_REGEX=Pattern.compile("t_(\\d+)");
	
	private static final Pattern SR_REGEX=Pattern.compile("/sr_(.+?)/");
	
	private static final Pattern COM_REGEX=Pattern.compile("/com_(.+?)/");
	
	@RequestMapping(value={"list/**"},method={RequestMethod.GET})
	public String list(){
		
		StringBuilder hql=new StringBuilder("select DISTINCT(mch) from Merchants mch inner join mch.serverRelations sr inner join mch.commodities com where 1=1");
		
		List<Serializable> params=new ArrayList<Serializable>();
		String path=this.request.getServletPath();
		Matcher m=AREA_REGEX.matcher(path);
		if(m.find()){
			hql.append(" and address.area.id=? ");
			params.add(m.group(1));
		}
		m=TYPE_REGEX.matcher(path);
		if(m.find()){
			hql.append(" and type.id=? ");
			params.add(m.group(1));
		}
		
		m=ADDR_REGEX.matcher(path);
		if(m.find()){
			hql.append(" and name like ? ");
			params.add("%"+m.group(1)+"%");
		}
		
		m=SR_REGEX.matcher(path);
		if(m.find()){
			hql.append(" and sr.residentialAreas.name like ? ");
			params.add("%"+m.group(1)+"%");
		}
		
		m=COM_REGEX.matcher(path);
		if(m.find()){
			hql.append(" and com.name.name like ? ");
			params.add("%"+m.group(1)+"%");
		}
		File f=null;
		List list= this.dao.list((CharSequence) this.createPagesSearchByPathVar(hql.toString(),params, 20));
		this.request.setAttribute("list", list);
		return "/views/list";
	}
}
